﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Input;
using ZiChen.SoXunLeiPan.Common;
using ZiChen.SoXunLeiPan.Service;
using ZiChen.SoXunLeiPan.ViewModel.Result;
using ZiChen.SoXunLeiPan.Views; // 引用SearchFilterParams

namespace ZiChen.SoXunLeiPan.ViewModel.View
{
    // 假设BaseViewModel已实现INotifyPropertyChanged，若未实现可替换为直接实现
    public class SearchViewModel : BaseViewModel
    {
        private readonly IHttpService _httpService = App.Services.GetService<IHttpService>();
        #region 字段与属性
        private string _searchText;
        private bool _isRefreshing;
        private bool _isLoadingMore;
        private bool _isEmptyVisible;
        private bool _isFirstLoad;
        private bool _isNotEmptyVisible = true;
        private string _emptyStateText = "暂无搜索结果"; // 空状态文本（支持加载失败提示）

        // 分页参数（新增：支持真实分页）
        private int _pageIndex = 1;
        private const int PageSize = 20;

        // 当前筛选条件（新增）
        private SearchFilterParams _currentFilter;

        public ObservableCollection<PanUrlList> FileList { get; } = new ObservableCollection<PanUrlList>();

        public string SearchText
        {
            get => _searchText;
            set => SetProperty(ref _searchText, value);
        }

        public bool IsRefreshing
        {
            get => _isRefreshing;
            set => SetProperty(ref _isRefreshing, value);
        }

        public bool IsLoadingMore
        {
            get => _isLoadingMore;
            set => SetProperty(ref _isLoadingMore, value);
        }
        public bool IsFirstLoad
        {
            get => _isFirstLoad;
            set => SetProperty(ref _isFirstLoad, value);
        }
        public bool IsEmptyVisible
        {
            get => _isEmptyVisible;
            set => SetProperty(ref _isEmptyVisible, value);
        }

        public bool IsNotEmptyVisible
        {
            get => _isNotEmptyVisible;
            set => SetProperty(ref _isNotEmptyVisible, value);
        }

        public string EmptyStateText
        {
            get => _emptyStateText;
            set => SetProperty(ref _emptyStateText, value);
        }

        public ICommand SearchCommand { get; }
        public ICommand LoadMoreCommand { get; }
        public ICommand ItemTappedCommand { get; }
        #endregion

        public SearchViewModel()
        {
            SearchCommand = new Command<SearchFilterParams>(ExecuteSearchCommand); // 支持筛选参数
            LoadMoreCommand = new Command(ExecuteLoadMoreCommand);
            ItemTappedCommand = new Command<string>(ExecuteItemTappedCommand);
            _currentFilter = new SearchFilterParams();
        }

        #region 核心命令实现
        // 搜索命令（支持筛选参数）
        private async void ExecuteSearchCommand(SearchFilterParams filter)
        {
            if (string.IsNullOrWhiteSpace(SearchText))
                return;

            // 更新当前筛选条件
            _currentFilter = filter ?? _currentFilter;

            // 重置分页+显示加载
            _pageIndex = 1;
            IsFirstLoad = _pageIndex == 1 ? true : false;
            IsRefreshing = true;
            IsEmptyVisible = false;
            IsNotEmptyVisible = true;
            EmptyStateText = "正在搜索，请稍后..."; // 加载中提示

            try
            {
                // 清空列表
                FileList.Clear();

                // 模拟网络延迟
                await Task.Delay(500);

                // 执行搜索（带筛选条件）
                var results = await PerformSearch(SearchText, _currentFilter, _pageIndex, PageSize);

                // 添加结果
                foreach (var item in results)
                {
                    FileList.Add(item);
                }
                if(FileList.Count == 0)
                {
                    IsNotEmptyVisible = false;
                    IsEmptyVisible = true;
                }
                else
                {
                    IsNotEmptyVisible = true;
                    IsEmptyVisible = false;
                }
                // 更新空状态
                EmptyStateText = "暂无搜索结果";
            }
            catch (Exception ex)
            {
                EmptyStateText = "搜索失败，请重试"; // 错误提示
                await Application.Current.MainPage.DisplayAlert("错误", $"搜索失败: {ex.Message}", "确定");
            }
            finally
            {
                IsRefreshing = false;
                IsFirstLoad = false;
            }
        }

        // 加载更多命令
        private async void ExecuteLoadMoreCommand()
        {
            if (IsFirstLoad || string.IsNullOrWhiteSpace(SearchText))
                return;

            if (IsLoadingMore) return;

            IsLoadingMore = true;

            try
            {
                // 分页+1
                _pageIndex++;

                // 模拟延迟
                await Task.Delay(1000);

                // 加载更多（带筛选条件）
                var moreResults = await PerformSearch(SearchText, _currentFilter, _pageIndex, PageSize, isLoadMore: true);

                // 无更多数据提示
                if (moreResults.Count == 0)
                {
                    _pageIndex--; // 回退分页
                }
                else
                {
                    foreach (var item in moreResults)
                    {
                        FileList.Add(item);
                    }
                }
            }
            catch (Exception ex)
            {
                _pageIndex--; // 回退分页
                await Application.Current.MainPage.DisplayAlert("错误", $"加载更多失败", "确定");
            }
            finally
            {
                IsLoadingMore = false;
            }
        }

        // 列表项点击
        private async void ExecuteItemTappedCommand(string md5)
        {
            await Shell.Current.GoToAsync($"/Details?md5={md5}");
        }
        #endregion

        #region 数据处理辅助方法
        // 执行搜索（整合筛选+分页）
        private async Task<List<PanUrlList>> PerformSearch(string searchText, SearchFilterParams filter,
                                                               int pageIndex, int pageSize, bool isLoadMore = false)
        {
            // 模拟API调用
            var rawResults = await MockSearchApi(searchText, filter,pageIndex, pageSize);

            return rawResults;
        }

        // 更新空状态
        //private void UpdateEmptyState()
        //{
        //    var hasData = FileList.Count > 0;
        //    IsEmptyVisible = !hasData && !IsRefreshing && !IsLoadingMore;
        //    IsNotEmptyVisible = hasData;
        //}
        #endregion

        #region 搜索API（带分页）
        private async Task<List<PanUrlList>> MockSearchApi(string searchText, SearchFilterParams filter, int pageIndex, int pageSize)
        {
            // 关键词含"空"时返回空结果（测试空状态）
            if (searchText.ToLower().Contains("空"))
            {
                return new List<PanUrlList>();
            }

            var secret = await SecureStorage.GetAsync("sign_secret");
            if (string.IsNullOrEmpty(secret))
            {
                throw new InvalidOperationException("签名密钥未配置");
            }

            var dict = new Dictionary<string, object>
            {
                { "timestamp", DateTimeOffset.UtcNow.ToUnixTimeSeconds() },
                { "nonce", Guid.NewGuid().ToString() }
            };
            var request = new Dictionary<string, object>
            {
                { "keyword", string.IsNullOrEmpty(searchText) ? "" : (searchText.Length > 30 ? searchText[..30] : searchText) },
                { "page", pageIndex },
                { "pageSize", pageSize },
                { "cate", filter.TabType },
                { "sizeType", filter.SizeOrder??"" },
                { "timeOrder", filter.TimeOrder??"" }
            };
            var signDict = dict.Union(request).ToDictionary(kv => kv.Key, kv => kv.Value);

            dict["sign"] = UrlSignTopRequest.Sign(signDict, secret);

            var queryString = string.Join("&", dict.Select(kv => $"{kv.Key}={Uri.EscapeDataString(kv.Value?.ToString() ?? "")}"));
            var url = $"/api/Search?{queryString}";

            var result = await _httpService.PostAsync<object, UnifyResult<List<PanUrlList>>>(url, request, "ApiClient");

            if (result?.Code == ResultCode.Success && result.Data != null)
            {
                return result.Data;
            }
            return new List<PanUrlList>();
        }
        
        #endregion
    }

    // 基类：实现INotifyPropertyChanged（若已有可删除）
    public class BaseViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
        {
            if (EqualityComparer<T>.Default.Equals(field, value)) return false;
            field = value;
            OnPropertyChanged(propertyName);
            return true;
        }
    }
}